using System.Text;
using Statistics.Count;
using UnityEngine;

namespace Statistics.Trace
{
    public class EventLog : TreeNode<EventLog, IEventLog>, IEventLog
    {
        private ValueStopwatch _sw;
        private string _log = string.Empty;

        public IEventLog AddChild()
        {
            var result = (EventLog)Create();
            result.Parent = this;
            return result;
        }

        public string EventName { get; set; } = string.Empty;

        public void BeginSample()
        {
            _sw = ValueStopwatch.StartNew();
        }

        public float ElapsedTimeMs => _sw.GetElapsedTime().Milliseconds;

        public void Log(string message)
        {
            _log = string.IsNullOrEmpty(_log) ? message : $"{_log}\n{message}";
        }

        public void EndSample()
        {
            var sb = new StringBuilder();
            // for (var i = 0; i < Level; i++)
            //     sb.Append("    ");
            sb.Append(_log);
            
            Debug.Log(sb.ToString());
        }

        private int Level
        {
            get
            {
                var result = 0;
                var parent = Parent;
                while (parent != null)
                {
                    result++;
                    parent = ((EventLog)parent).Parent;
                }
                return result;
            }
        }
        
        public static IEventLog Create()
        {
            var result = new EventLog();
            return result;
        }
    }
}